﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Web.UI;
using shfa.snomtastic.admin.components;
using shfa.snomtastic.data;
using shfa.snomtastic.data.business;
using shfa.snomtastic.data.security;
using Telerik.Web.UI;
using System.Threading;

namespace shfa.snomtastic.admin.editcontrols
{
    public partial class ePhone : EditBase
    {

        #region Public Members

        public bool IsNewItem
        {
            get { return (ActiveItemId == Guid.Empty); }
        }

        public Guid ActiveItemId
        {
            get { return (hfItemId.Value != string.Empty) ? new Guid(hfItemId.Value) : Guid.Empty; }
            set { hfItemId.Value = value.ToString(); }
        }

        public AppConfig ac = new AppConfig();


        #endregion

        #region Page

        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void Page_Init(object sender, EventArgs e)
        {
            if (ItemId != Guid.Empty)
                ActiveItemId = ItemId;

            if (ActiveItemId != Guid.Empty)
            {
                bindItem();
            }
            else
            {
                bindLists(new PhoneInfo());

            }
        }

        #endregion

        #region Helpers

        private void bindItem()
        {
            PhoneController pc = new PhoneController();
            PhoneInfo pi = pc.SelectPhone(ActiveItemId);
            if (pi != null)
            {
                txtMacAddress.Text = pi.MacAddress;


                btnConfig.OnClientClick = "window.open('../phone/settings/settings.aspx?mac=" + pi.MacAddress + "', 'ConfigWindow')";


                txtUserAgent.Text = pi.UserAgent;
                chkRegistrationFailed.Checked = pi.RegistrationFailed;
                txtSerialNumber.Text = pi.SerialNumber;
                txtIpAddress.Text = pi.IpAddress;
                hlManagePhone.NavigateUrl = "http://" + pi.IpAddress;
                txtLastUpdated.Text = common.LongDateTime(pi.UpdatedDate);
               


                lblHeaderLeft.Text = "Phone - " + pi.MacAddress;
                lblHeaderRight.Text = "[No User]";
                if (pi.UserId != null)
                {
                    UserController uc = new UserController();
                    UserInfo ui = uc.SelectUser(pi.UserId);
                    if(ui!=null)
                        lblHeaderRight.Text = ui.UserName;

                }

                 bindLists(pi);

            }


        }

        private void bindLists(PhoneInfo pi)
        {


            // Configurations
            ConfigurationController cc = new ConfigurationController();
            List<ConfigurationInfo> ciList = cc.SelectConfigurations("Name Asc");
            ddConfiguration.DataSource = ciList;
            ddConfiguration.DataTextField = "Name";
            ddConfiguration.DataValueField = "ConfigurationId";
            ddConfiguration.DataBind();
            ddConfiguration.Items.Insert(0, new RadComboBoxItem("<None>", Guid.Empty.ToString()));
            if (pi.ConfigurationId != Guid.Empty)
                ddConfiguration.Items.FindItemByValue(pi.ConfigurationId.ToString()).Selected = true;



            // users
            UserController uc = new UserController();
            List<UserInfo> uiList = uc.SelectUsers("UserName Asc");
            ddUsers.DataSource = uiList;
            ddUsers.DataTextField = "UserName";
            ddUsers.DataValueField = "UserId";
            ddUsers.DataBind();
            ddUsers.Items.Insert(0, new RadComboBoxItem("<None>", Guid.Empty.ToString()));
            if (pi.UserId != Guid.Empty)
                ddUsers.Items.FindItemByValue(pi.UserId.ToString()).Selected = true;


            // Model
            if (pi.ModelId != Guid.Empty)
            {
                ModelController mc = new ModelController();
                ModelInfo mi = mc.SelectModel(pi.ModelId);
                if (mi != null)
                {
                    txtModel.Text = mi.Name;
                }
            }


            // Firmware
            if (pi.FirmwareId != Guid.Empty)
            {
                FirmwareController fc = new FirmwareController();
                FirmwareInfo fi = fc.SelectFirmware(pi.FirmwareId);
                if (fi != null)
                {
                    txtFirmware.Text = fi.Version;
                }
            }


        }

        #endregion

        #region Action Event Helpers

        private void SaveItem()
        {
            if (Page.IsValid)
            {
                PhoneController pc = new PhoneController();
                PhoneInfo pi = new PhoneInfo();

                if (!IsNewItem)
                    pi = pc.SelectPhone(ActiveItemId);


                pi.SerialNumber = txtSerialNumber.Text;
                pi.RegistrationFailed = chkRegistrationFailed.Checked;

                if (ddUsers.SelectedIndex > 0)
                    pi.UserId = new Guid(ddUsers.SelectedValue);
                else if (!IsNewItem)
                    pi.UserId = Guid.Empty;

                if (ddConfiguration.SelectedIndex > 0)
                    pi.ConfigurationId = new Guid(ddConfiguration.SelectedValue);
                else if (!IsNewItem)
                    pi.ConfigurationId = Guid.Empty;


                if (IsNewItem)
                {
                    pi.CreatedDate = DateTime.UtcNow;
                    pi.Model = "";
                    pi.Firmware = "";
                    pi.BootLoader = "";
                    pc.InsertPhone(pi);
                }
                else
                {
                    pc.UpdatePhone(pi);
                }

                RaiseNavEvent(this, new NavEventArgs("ePhones", ActiveItemId));
            }


        }

        private void DeleteItem()
        {
            PhoneController pc = new PhoneController();
            pc.DeletePhone(ActiveItemId);
            RaiseNavEvent(this, new NavEventArgs("ePhones", ActiveItemId));
        }


        private void SendPhoneCommand(PhoneCommand.CommandType cmd)
        {
            SendPhoneCommand(cmd, false);
        }

        private void SendPhoneCommand(PhoneCommand.CommandType cmd, bool resetPassword)
        {

            RijndaelEnhanced re = new RijndaelEnhanced();

            PhoneController pc = new PhoneController();
            PhoneInfo pi = pc.SelectPhone(ActiveItemId);
            if (pi != null)
            {
                PhoneCommand phCmd = new PhoneCommand(pi, cmd);
                Thread oThread = new Thread(new ThreadStart(phCmd.SendCommand));
                oThread.Start();
                if (resetPassword)
                {
                    pi.HttpClientPass = string.Empty;
                    pc.UpdatePhone(pi);
                }

            }


        }


        #endregion

        #region EditBase

        public override void EditBase_ActionEvent(object sender, ActionClickArgs e)
        {
            switch (e.ActionName)
            {
                case "Save":
                    SaveItem();
                    break;
                case "Config":
                    RaiseNavEvent(this, new NavEventArgs("eShowConfig", ActiveItemId));
                    break;
                case "Delete":
                    DeleteItem();
                    break;
                case "Register":
                    SendPhoneCommand(PhoneCommand.CommandType.Reregister);
                    break;
                case "Reboot":
                    SendPhoneCommand(PhoneCommand.CommandType.Reboot);
                    RaiseNavEvent(this, new NavEventArgs("ePhones", ActiveItemId));
                    break;
                case "Reset":
                    SendPhoneCommand(PhoneCommand.CommandType.Reset, true);
                    RaiseNavEvent(this, new NavEventArgs("ePhones", ActiveItemId));
                    break;
                case "Return":
                    RaiseNavEvent(this, new NavEventArgs("ePhones", ActiveItemId));
                    break;
                default:
                    break;
            }
        }

        public override List<ActionInfo> ActionList
        {
            get
            {
                List<ActionInfo> al = new List<ActionInfo>();
                al.Add(new ActionInfo("Save", "Save Changes", "~/images/icons/save.png", "", true, true));
                al.Add(new ActionInfo("Config", "Show Settings", "~/images/icons/settings.png", "", true, true));
                al.Add(new ActionInfo("Register", "Re-Register User", "~/images/icons/user.png"));
                al.Add(new ActionInfo("Reboot", "Reboot Phone", "~/images/icons/reboot.png", "Are you sure you wish to reboot this phone?", true));
                al.Add(new ActionInfo("Reset", "Reset Phone", "~/images/icons/reset.png", "Resetting this phone will remove all settings", true));
                al.Add(new ActionInfo("Delete", "Delete Phone", "~/images/icons/delete.png", "Are you sure you want to delete this phone", true));
                al.Add(new ActionInfo("Return", "Return", "~/images/icons/undo.png"));

                return al;
            }
        }

        #endregion


    }
}